package me

import (
	"dustbe/util"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
	"time"
	"github.com/gin-gonic/gin"
)


func BiliBiliBangumi(c *gin.Context) {
	file, error := os.Open(bangumiJson)
	if error != nil {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "msg" : "本地缓存文件打开错误"})
		return
	}
	fs, error := file.Stat()
	if error != nil {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "msg" : "文件状态获取错误"})
		return
	}
	file.Close()
	// 如果今天还没更新，拉取更新信息
	if fs.ModTime().Day() != time.Now().Day() {
		res, err := http.Get(bangumiAPI)
		if err == nil {
			rawContent, _ := ioutil.ReadAll(res.Body)
			content, _ := util.UnicodeToZh(rawContent)
			content = strings.ReplaceAll(content, `\/`, `/`)
			ioutil.WriteFile(bangumiJson, []byte(content), 0777)
		}
		res.Body.Close()
	}

	fileByte, err := ioutil.ReadFile(bangumiJson)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "msg" : "本地文件打开错误"})
		return
	}
	data := make(gin.H)
	json.Unmarshal(fileByte, &data)
	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : data["data"]})
}